package com.atguigu.gmall.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送消息
     * @param exchange 交换机
     * @param routingKey 路由key
     * @param object 消息主体
     * @return
     */
    public boolean sendMessage(String exchange,String routingKey,Object object){

        //创建一个CorrelationData对象
        GmallCorrelationData correlationData=new GmallCorrelationData();
        //生成id
        String correlationId = UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(correlationId);
        //交换机
        correlationData.setExchange(exchange);
        //路由key
        correlationData.setRoutingKey(routingKey);
        //消息本地
        correlationData.setMessage(object);
        //将对象存储到redis
        redisTemplate.opsForValue().set(
                correlationId,
                JSONObject.toJSONString(correlationData),
                10,
                TimeUnit.MINUTES);



//        rabbitTemplate.convertAndSend(exchange,routingKey,object);
        rabbitTemplate.convertAndSend(exchange,routingKey,object,correlationData);


        return true;
    }


    /**
     * 延迟消息发送
     * @param exchange 交换机
     * @param routingKey 路由key
     * @param object 消息本地
     * @param delayTime 延迟时间
     * @return
     */
    public boolean sendDelayedMessage(String exchange,String routingKey,Object object,int delayTime){

        //创建一个CorrelationData对象
        GmallCorrelationData correlationData=new GmallCorrelationData();
        //生成id
        String correlationId = UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(correlationId);
        //交换机
        correlationData.setExchange(exchange);
        //路由key
        correlationData.setRoutingKey(routingKey);
        //消息本地
        correlationData.setMessage(object);
        //设置延迟消息
        correlationData.setDelay(true);
        //设置延迟时间
        correlationData.setDelayTime(delayTime);

        //存储到redis
        redisTemplate.opsForValue().set(correlationId, JSON.toJSONString(correlationData),10,TimeUnit.MINUTES);
        //发送消息
        rabbitTemplate.convertAndSend(exchange,routingKey,object,message -> {

            //设置延迟时间
            message.getMessageProperties().setDelay(delayTime*1000);

            return message;
        },correlationData);



        return true;
    }

}
